package common

/*
 * @Desc: Web接口返回
 * @author: bsyz
 * @version: v1.0.0
 */

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"reflect"
)

type response struct {
	context *gin.Context
}

type ResultData struct {
	Code int `json:"code"`
	Data any `json:"data"`
}

func NewResponse(ctx *gin.Context) *response {
	return &response{
		context: ctx,
	}
}

func (r *response) Success() {
	r.context.JSON(http.StatusOK, ResultData{
		Code: RETURN_SUCCESS,
		Data: "操作成功",
	})
}

func (r *response) SuccessWithData(data interface{}) {
	defer func() {
		if err := recover(); err != nil {
			r.context.JSON(http.StatusOK, ResultData{
				Code: RETURN_SUCCESS,
				Data: data,
			})
		}
	}()

	_, exist := reflect.TypeOf(data).FieldByName("ID")
	if exist {
		value := reflect.ValueOf(data).FieldByName("ID")
		id, ok := value.Interface().(int64)
		if id == 0 && ok {
			r.context.JSON(http.StatusOK, ResultData{
				Code: RETURN_SUCCESS,
				Data: nil,
			})
			return
		}
	}
	r.context.JSON(http.StatusOK, ResultData{
		Code: RETURN_SUCCESS,
		Data: data,
	})
}

func (r *response) Error(data interface{}) {
	result := ResultData{
		Code: RETURN_FAILED,
		Data: data,
	}
	r.context.Abort()
	r.context.JSON(http.StatusOK, result)
}

func (r *response) ErrorWithCode(data interface{}, code int) {
	result := ResultData{
		Code: RETURN_FAILED,
		Data: data,
	}
	r.context.Abort()
	r.context.JSON(code, result)
}
